package com.minelx.statementplus.ui.form.dao;

import com.minelx.sqlstructures.statements.clause.Field;
import com.minelx.sqlstructures.statements.clause.SelectClauseBuilder;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class SelectClauseListModel extends AbstractListModel {
	private final SelectClauseBuilder selectClauseBuilder;

	private List<Field> fields;

	public SelectClauseListModel(SelectClauseBuilder selectClauseBuilder) {
		this.selectClauseBuilder = selectClauseBuilder;
		refreshAll();
	}

	@Override
	public int getSize() {
		return fields.size();
	}

	@Override
	public Object getElementAt(int index) {
		return fields.get(index);
	}

	public void addElement(Field added) {
		int index = getSize();
		selectClauseBuilder.add(added);
		fireIntervalAdded(this, index, index);
		refreshAll();
	}

	public void removeElement(int index) {
		selectClauseBuilder.remove(fields.get(index));
		fireIntervalRemoved(this, index, index);
		refreshAll();
	}

	public void clear() {
		selectClauseBuilder.removeAll();
		fireIntervalRemoved(this, 0, getSize());
		refreshAll();
	}

	private void refreshAll() {
		fields = new ArrayList<>(selectClauseBuilder.getFields());
	}
}
